package main

import (
	"crypto/rand"
	"fmt"
	"github.com/tjfoc/gmsm/sm2"
	"github.com/tjfoc/gmsm/x509"
	"io/ioutil"
	"os"
)

func main() {
	GenerateKey()
	msg := []byte("test")
	skBytes, err := ioutil.ReadFile("ca.key")
	if err != nil {
		panic(err)
	}
	pkBytes, err := ioutil.ReadFile("ca.crt")
	if err != nil {
		panic(err)
	}
	data, err := Sign(msg, skBytes)
	if err != nil {
		panic(err)
	}
	ok, err := Verify(msg, []byte(data), pkBytes)
	if err != nil {
		panic(err)
	}
	fmt.Println(ok)
}

func GenerateKey() {
	key, err := os.OpenFile("ca.key", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		panic(err)
	}
	crt, err := os.OpenFile("ca.crt", os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0666)
	if err != nil {
		panic(err)
	}
	sk, err := sm2.GenerateKey(rand.Reader)
	if err != nil {
		panic(err)
	}
	skBytes, err := x509.WritePrivateKeyToPem(sk, nil)
	if err != nil {
		panic(err)
	}
	key.Write(skBytes)
	pkBytes, err := x509.WritePublicKeyToPem(&sk.PublicKey)
	if err != nil {
		panic(err)
	}
	crt.Write(pkBytes)
}
